from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
# Create your views here.
from .. models import Cates

def get_cate_all():
    # 定义函数 #处理数据的顺序
    data = Cates.objects.extra(select={'paths': 'concat(path,id)'}).order_by('paths')
    for i in data:
        l = i.path.count(',')
        i.sub = l * '|----'
        if i.pid == 0:
            i.pname = '顶级分类'
        else:
            pob = Cates.objects.get(id=i.pid)
            i.pname = pob.name
    return data

#分类列表
def cate_index(request):
    # data = Cates.objects.all()
    data = get_cate_all()


    contex = {'catelist':data}


    return render(request,'myadmin/cates/index.html',contex)



# 分类添加
def cate_add(request):
    if request.method == 'POST':
        # 接受数据
        data = {}
        data['name'] = request.POST.get('name')
        data['pid'] = request.POST.get('pid')
        # data['path'] = request.POST.get('pid')+','

        # path路劲判断
        if data['pid'] == '0':
            data['path'] = '0,'

        else:
            pob = Cates.objects.get(id=data['pid'])
            data['path'] = pob.path+data['pid']+','


        # 数据 入库
        print(data)
        # print(pob)
        ob = Cates(**data)
        ob.save()
        # return HttpResponse('123')
        return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_cate_index')+'";</script>')
    else:
        # 获取分类
        catelist =get_cate_all()
        #分配数据
        context = {'catelist':catelist}

        # 加载模板
        return render(request,'myadmin/cates/add.html',context)

#分类删除

def cate_del(request):
    cid = request.GET.get('cid')
    # 获取对象
    #
    #判断是否有子类
    res = Cates.objects.filter(pid=cid).count()
    if res:
        #有子类
        data = {'mag':'当前有子类不能删除','code':'1'}
        return JsonResponse(data)
        #   判断是否有商品

        #删除对象
    ob = Cates.objects.get(id=cid)
    ob.delete()
    return JsonResponse({'msg':'删除成功','code':'0'})


def cate_edit(request):
    try:
        # 获取 参数
        cid = request.GET.get('cid')
        newname = request.GET.get('newname')
        print(cid)
        print(newname)
        # 获取对象
        ob = Cates.objects.get(id=cid)
        ob.name = newname
        # 修改属性
        ob.save()
        data = {'msg':'更新成功','code':0}
    except:
        data = {'msg':'更新失败','code':1}

    # 返回结果
    return JsonResponse(data)